package com.globalHandler;

import com.controller.base.BaseController;
import com.controller.base.Response;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler extends BaseController {

    @ExceptionHandler(NullPointerException.class)
    public Response NullPointerException(NullPointerException ex) {
        ex.printStackTrace();
        return fail().setMsg("空指针异常");
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public Response DataIntegrityViolationException(DataIntegrityViolationException ex) {
        ex.printStackTrace();
        return fail().setMsg("数据处理异常");
    }

    @ExceptionHandler(BindException.class)
    public Response fromException(BindException ex) {
        return BaseController.fail(ex.getFieldErrors().get(0).getDefaultMessage());
    }


    @ExceptionHandler(Exception.class)
    public Response OtherException(Exception ex) {
        ex.printStackTrace();
        return fail().setMsg("未知异常");
    }
}
